package com.syn.michat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.syn.michat.constant.MessageContants;
import com.syn.michat.im.WebSocketSessionManager;
import com.syn.michat.im.model.Package;
import com.syn.michat.im.model.ScreenshotMsgEntity;
import com.syn.michat.im.service.PackageService;
import com.syn.michat.model.ResponseEntity;
import com.syn.michat.pojo.ScreenshotsReport;
import com.syn.michat.pojo.User;
import com.syn.michat.service.ScreenshotsReportService;
import com.syn.michat.service.UserService;
import com.syn.michat.util.BlowfishUtil;
import com.syn.michat.util.ResponseErrorUtil;
import com.syn.michat.util.exception.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.Session;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping(value = "/screenshots",produces = "application/json;charset=UTF-8")
public class ScreenshotsReportController {

    @Autowired
    private UserService userService;
    @Autowired
    private PackageService packageService;
    @Autowired
    private ScreenshotsReportService screenshotsReportService;

    @PostMapping("/report")
    public String report(HttpServletRequest request, @RequestParam String fileName, @RequestParam String targetId, @RequestParam String time) {
        User user = (User) request.getAttribute("user");

        ScreenshotsReport report = new ScreenshotsReport();
        report.setFileName(fileName);
        report.setTargetId(targetId);
        report.setTime(Long.valueOf(time).longValue());
        report.setUserId(user.getUserId());
        try {
            screenshotsReportService.save(report);
            sendScreenshotMsg(user.getUserId(), targetId, report);
        } catch (Exception e) {
            return JSON.toJSONString(ResponseErrorUtil.convertException(e));
        }

        return JSON.toJSONString(new ResponseEntity());
    }

    @GetMapping("/list")
    public String list(HttpServletRequest request, @RequestParam String uuid) {
        User user = (User) request.getAttribute("user");

        try {
            List<ScreenshotsReport> list = screenshotsReportService.list(user.getUserId(), uuid);
            HashMap<String, Object> map = new HashMap();
            map.put("screenshotList", list);
            ResponseEntity res = new ResponseEntity(map);
            return JSON.toJSONString(res);
        } catch (ClientException e) {
            return JSON.toJSONString(ResponseErrorUtil.convertException(e));
        }
    }

    private void sendScreenshotMsg(String senderId, String targetId, ScreenshotsReport report) throws Exception {
        User sender = userService.findUser(senderId);
        User receiver = userService.findUser(targetId);
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        ScreenshotMsgEntity msg = new ScreenshotMsgEntity();
        msg.setUuid(uuid);
        msg.setMsgType(MessageContants.SCREENSHOT);
        msg.setReceiver(receiver);
        msg.setSender(sender);
        msg.setTime(timestamp.getTime());
        msg.setScreenshotUser(sender);
        msg.setScreenshotTime(report.getTime());
        msg.setScreenshotImageName(report.getFileName());

        Package aPackage = new Package();
        aPackage.setType(Package.PACKAGE_TYPE_MESSAGE);
        aPackage.setData(BlowfishUtil.encrypt(JSON.toJSONString(msg, SerializerFeature.DisableCircularReferenceDetect)));

        // 给双方都发socket消息
        Session rSession = WebSocketSessionManager.sessionMap.get(targetId);
        packageService.sendPackage(aPackage, rSession);

        Session sSession = WebSocketSessionManager.sessionMap.get(senderId);
        packageService.sendPackage(aPackage, sSession);
    }
}
